package controller

import (
	"bytes"
	"context"
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"net/http"
	"strconv"
	"strings"
	"testGin/entity"
	"testGin/tool"
	"time"
)

// 文件上传
func Upload(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	ty := c.PostForm("type")
	title := c.PostForm("title")
	// 接受文件
	file, fileHeader, _ := c.Request.FormFile("file")
	// 转为byte
	byteData := make([]byte, fileHeader.Size)
	file.Read(byteData)

	var user entity.User
	GetDB().Where("id = ?", id).First(&user)

	key := "lixianhe/" + strconv.FormatInt(time.Now().UnixMilli(), 10)
	saveMp4Entry := base64.URLEncoding.EncodeToString([]byte(Bucket + ":" + key))
	fopVframe := fmt.Sprintf("vframe/jpg/offset/10|saveas/%s", storage.EncodedEntry(Bucket, key+".jpg"))
	fopAvthumb := "avthumb/mp4|saveas/" + saveMp4Entry

	//数据处理指令，支持多个指令
	fopBatch := []string{fopAvthumb, fopVframe}
	fops := strings.Join(fopBatch, ";")
	putPolicy := storage.PutPolicy{
		Scope:              fmt.Sprintf("%s:%s", Bucket, key+".mp4"),
		PersistentOps:      fops,
		PersistentPipeline: Pipline,
	}
	upToken := putPolicy.UploadToken(qbox.NewMac(AccessKey, SecretKey))

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = true
	cfg.UseCdnDomains = true
	resumeUploader := storage.NewResumeUploaderV2(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.RputV2Extra{}
	resumeUploader.Put(context.Background(), &ret, upToken, key+".mp4", bytes.NewReader(byteData), fileHeader.Size, &putExtra)

	// 文件的hash和key插入数据库
	var video entity.Video
	video.Uid = id
	video.Key = ret.Key
	video.Hash = ret.Hash
	video.Type = ty
	video.Title = title
	video.Cover = key + ".jpg"
	GetDB().Select("key", "hash", "type", "uid", "cover", "title").Create(&video)

	var upload entity.UserVideoCollectLoveUpload
	upload.Uid = id
	upload.Vid = video.Id
	GetDB().Table("upload").Select("uid", "vid").Create(&upload)
	// 返回JSON格式的数据
	c.JSON(http.StatusOK, tool.R{
		200, "上传完成", video,
	})
}
